package net.pinnoocle.playservice.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.pinnoocle.playcommon.exception.ShopException;
import net.pinnoocle.playcommon.response.ErrorCode;
import net.pinnoocle.playcommon.utils.BigDecimalMathUtil;
import net.pinnoocle.playcommon.utils.ConvertUtils;
import net.pinnoocle.playcommon.utils.HelpUtils;
import net.pinnoocle.playdao.dao.OrderDao;
import net.pinnoocle.playdao.entity.*;

import net.pinnoocle.playdao.entity.page.PageModel;
import net.pinnoocle.playdao.entity.page.PageQuery;
import net.pinnoocle.playdao.entity.shopPc.order.*;
import net.pinnoocle.playdao.entity.web.order.*;
import net.pinnoocle.playdao.entity.web.shop.OrderDetailVo;
import net.pinnoocle.playdao.entity.web.shop.OrderListPageVo;
import net.pinnoocle.playdao.entity.web.shop.OrderListSearchParams;
import net.pinnoocle.playservice.service.PayService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 订单表(Order)表服务实现类
 *
 * @author ye
 * @since 2021-11-01 14:45:24
 */
@Service("orderService")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> {

    @Autowired
    UserServiceImpl userService;
    @Autowired
    UserGroupServiceImpl userGroupService;
    @Autowired
    ScriptServiceImpl scriptService;
    @Autowired
    UserCouponServiceImpl userCouponService;
    @Autowired
    PayService payService;
    @Autowired
    ScriptEvaluateServiceImpl scriptEvaluateService;
    @Autowired
    UserScriptServiceImpl userScriptService;
    @Autowired
    ShopServiceImpl shopService;
    @Autowired
    UserAppointOrderServiceImpl userAppointOrderService;
    @Autowired
    UserLevelServiceImpl userLevelService;
    @Autowired
    ShopFinanceServiceImpl shopFinanceService;
    @Autowired
    ShopStatisticsServiceImpl shopStatisticsService;
    @Autowired
    GroupServiceImpl groupService;

    /**
     * 买单页回显
     * @return
     */
    public PayBillPageVo billPage(){
        String userId = userService.getUserId();
        UserGroup userGroup = userGroupService.getOne(new QueryWrapper<UserGroup>()
                .lambda()
                .eq(UserGroup::getUserId, userId)
                .eq(UserGroup::getIsPay, 0));
        if(Objects.isNull(userGroup)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"没有需要支付的订单");
        }
        PayBillPageVo payBillPageVo = new PayBillPageVo();
        Shop shop = shopService.getById(userGroup.getShopId());
        payBillPageVo.setShopName(shop.getShopName());
        payBillPageVo.setLogo(shop.getLogo());
        //用户是否支付了定金
        UserAppointOrder appointOrder = userAppointOrderService.getOne(new QueryWrapper<UserAppointOrder>()
                .lambda()
                .eq(UserAppointOrder::getUserId, userId)
                .eq(UserAppointOrder::getGroupId, userGroup.getGroupId())
                .eq(UserAppointOrder::getHasPay,1));
        if(Objects.isNull(appointOrder)){
            payBillPageVo.setAppointOrderPay(0);
        }else{
            payBillPageVo.setAppointOrderPay(1);
            payBillPageVo.setAppointPrice(appointOrder.getPayAmount());
        }
        return payBillPageVo;
    }

    /**
     * 用户买单（有且只有一个组局未买单）
     * @return
     */
    public String payBill(PayBillParams billParams){
        String userId = userService.getUserId();
        UserGroup userGroup = userGroupService.getOne(new QueryWrapper<UserGroup>()
                .lambda()
                .eq(UserGroup::getUserId, userId)
                .eq(UserGroup::getIsPay, 0));
        if(Objects.isNull(userGroup)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"没有需要支付的订单");
        }
        Order noPayOrder = this.getOne(new QueryWrapper<Order>().lambda()
                .eq(Order::getUserGroupId, userGroup.getGroupId())
                .eq(Order::getUserId, userId)
                .eq(Order::getHasPay, 0), false);
        if(Objects.nonNull(noPayOrder)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"已经买过单了，直接去支付吧");
        }
        double payPrice = billParams.getMoney();
        Order order = new Order();
        String userCouponId = billParams.getUserCouponId();
        if(StringUtils.isNotBlank(userCouponId)){
            UserCoupon usrCoupon = userCouponService.getById(userCouponId);
            if(Objects.isNull(usrCoupon)){
                throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"优惠券不存在");
            }
            double newPrice = BigDecimalMathUtil.add(payPrice, usrCoupon.getFaceValue());
            order.setDiscountPrice(usrCoupon.getFaceValue());
            order.setTotalPrice(newPrice);
            order.setUserCouponId(userCouponId);
        }
        order.setOrderNo(HelpUtils.getOrderNumber());
        order.setUserId(userId);
        order.setUserGroupId(userGroup.getGroupId());
        order.setScriptId(userGroup.getScriptId());
        order.setShopId(userGroup.getShopId());
        order.setPayPrice(payPrice);
        order.setMasterId(userGroup.getMasterId());
        order.setAppointPrice(billParams.getAppointPrice());
        order.setCreatedTime(new Date());
        boolean result = this.save(order);
        if(result){
            return order.getOrderId();
        }
        return "";
    }

    /**
     * 用户订单列表
     * @param searchVo
     * @return
     */
    public PageModel<UserOrderListPageVo> orderList(UserOrderListSearchVo searchVo){
        Map<String,Object> pageMap = new HashMap<>();
        pageMap.put("page",String.valueOf(searchVo.getPage()));
        pageMap.put("pageSize",String.valueOf(searchVo.getPageSize()));

        if(searchVo.getUserId() == null){
            searchVo.setUserId(userService.getUserId());
        }
        Page<UserOrderListPageVo> list = this.baseMapper.orderList(
                new PageQuery<Order>(pageMap).getPage(),searchVo);
        List<UserOrderListPageVo> records = list.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageModel<>(list, new ArrayList<>());
        }
        for (UserOrderListPageVo item : records){
            if(StringUtils.isNotBlank(item.getScriptCateId())){
                String cateNames = scriptService.getNamesByIds(item.getScriptCateId(), 0);
                item.setScriptCateName(cateNames);
            }
        }
        return new PageModel<>(list, records);
    }

    /**
     * 订单详情
     * @param orderId
     * @return
     */
    public UserOrderDetailVo orderDetail(String orderId){
        UserOrderDetailVo userOrderDetailVo = this.baseMapper.orderDetail(orderId);
        if(Objects.nonNull(userOrderDetailVo) && StringUtils.isNotBlank(userOrderDetailVo.getScriptCateId())){
            String cateNames = scriptService.getNamesByIds(userOrderDetailVo.getScriptCateId(), 0);
            userOrderDetailVo.setScriptCateName(cateNames);
        }
        return userOrderDetailVo;
    }

    /**
     * 订单支付
     * @param orderId
     * @return
     */
    public PayInfo billGoPay(String orderId) throws Exception {
        Order order = this.getById(orderId);
        if(Objects.isNull(order)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"订单不存在");
        }
        User user = userService.getById(order.getUserId());
        if(Objects.isNull(user)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"支付异常");
        }
        String userCouponId = order.getUserCouponId();
        UserCoupon userCoupon = userCouponService.getById(userCouponId);
        //使用了优惠券并且优惠券过期了
        if(Objects.nonNull(userCoupon) && userCoupon.getEffectStatus() == 2){
            double newPryPrice = BigDecimalMathUtil.add(order.getPayPrice(), order.getDiscountPrice());
            order.setPayPrice(newPryPrice);
            order.setDiscountPrice(0.00);
            order.setUserCouponId("");
            this.updateById(order);
        }
        PayInfo payInfo = payService.payOrder(order.getShopId(), user.getOpenId(), order.getPayPrice(),2);
        if(Objects.nonNull(payInfo)){
            order.setOutTradeNo(payInfo.getOutTradeNo());
            boolean result = this.updateById(order);
            if(!result){
                return null;
            }
        }
        return payInfo;
    }

    /**
     * 订单支付状态查询
     * @param orderId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String orderQuery(String orderId) {
        try {
            Order order = this.getById(orderId);
            if(order.getHasPay() == 1){
                return "success";
            }
            OrderInfoVo orderInfoVo = payService.orderQuery(order.getOutTradeNo());
            String tradeState = orderInfoVo.getTradeState();
            if(Objects.equals(tradeState, "SUCCESS")){
                order.setHasPay(1);
                order.setPayTime(orderInfoVo.getPayTime());
                order.setTransactionId(orderInfoVo.getTransactionId());
                this.updateById(order);
                handleOrder(order);
                return "success";
            }
        } catch (Exception e) {
            log.info("订单查询失败："+e.getMessage());
        }
        return "fail";
    }

    /**
     * 订单支付成功处理订单
     * @param order
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean handleOrder(Order order){
        String userCouponId = order.getUserCouponId();
        String userGroupId = order.getUserGroupId();//组局id
        String userId = order.getUserId();
        try {
            //更新优惠券为已使用
            UserCoupon userCoupon = userCouponService.getById(userCouponId);
            if(Objects.nonNull(userCoupon) && userCoupon.getEffectStatus() == 1){
                userCoupon.setStatus(1);
                userCouponService.updateById(userCoupon);
            }
            //更新组局支付人数
            Group group = groupService.getById(userGroupId);
            if(Objects.nonNull(group)){
                group.setPayUserNumber(group.getPayUserNumber()+1);
                groupService.updateById(group);
            }
            //更新用户组局为已支付
            UserGroup userGroup = userGroupService.getOne(new QueryWrapper<UserGroup>()
                    .lambda()
                    .eq(UserGroup::getUserId, userId)
                    .eq(UserGroup::getGroupId, userGroupId));
            //UserGroup userGroup = userGroupService.getById(userGroupId);
            if(Objects.nonNull(userGroup)){
                userGroup.setIsPay(1);
                userGroupService.updateById(userGroup);
            }
            Script script = scriptService.getById(order.getScriptId());
            //更新用户信息
            int userPlayTimes = userService.getUserPlayTimes(order.getUserId());
            int memberLevelId = userLevelService.getMemberLevelId(userPlayTimes + 1);
            double totalExpensePrice = BigDecimalMathUtil.add(order.getPayPrice(), order.getAppointPrice());
            userService.updateShopUser(order.getUserId(),script.getScriptTime(),totalExpensePrice,memberLevelId);
            //更新统计
            shopStatisticsService.grandShopStatisticsOrder(order.getShopId(),userPlayTimes);
            //更新剧本信息
            double orderPrice = BigDecimalMathUtil.add(order.getPayPrice(),order.getAppointPrice());
            script.setPlayNum(script.getPlayNum()+1);
            double totalAmount = BigDecimalMathUtil.add(script.getTotalAmount(), orderPrice);
            script.setTotalAmount(totalAmount);
            script.setLastIncomeDate(new Date());
            scriptService.updateById(script);
            //记录门店收入
            ShopFinance shopFinance = new ShopFinance();
            shopFinance.setShopId(order.getShopId());
            shopFinance.setAmount(order.getPayPrice());
            shopFinance.setFinanceType(0);
            shopFinance.setSourceName("订单收入");
            shopFinance.setOrderNo(order.getOrderNo());
            shopFinance.setCreatedTime(new Date());
            shopFinanceService.save(shopFinance);
        } catch (Exception e) {
            log.info("handleOrder_error:"+e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 剧本评星
     * @param orderId
     * @param starNum
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean evaluateScript(String orderId,Integer starNum){
        Order order = this.getById(orderId);
        if(Objects.isNull(order)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"订单不存在");
        }
        String scriptId = order.getScriptId();
        Script script = scriptService.getById(scriptId);
        if(Objects.isNull(script)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"剧本不存在");
        }
        if(starNum <= 0){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"最低一颗星");
        }
        String userId = userService.getUserId();
        try {
            ScriptEvaluate scriptEvaluate = new ScriptEvaluate();
            scriptEvaluate.setUserId(userId);
            scriptEvaluate.setScriptId(scriptId);
            scriptEvaluate.setStarNum(starNum);
            scriptEvaluate.setCreatedTime(new Date());
            boolean result = scriptEvaluateService.save(scriptEvaluate);
            if(result){
                //更新剧本平均分
                double score = scriptService.calculateScriptScore(scriptId);
                script.setScore(score);
                scriptService.updateById(script);
                //更新评价状态
                order.setHasEvaluate(1);
                this.updateById(order);
            }
            return result;
        } catch (Exception e) {
            log.info("evaluateScript_error:"+e.getMessage());
        }
        return false;
    }

    /**
     * 门店端买单记录
     * @param params
     * @return
     */
    public OrderDetailVo shopOrderList(OrderListSearchParams params){
        if(params.getShopId() == null){
            params.setShopId(userService.getGlobalShopId());
        }
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        String yearMonth = params.getYearMonth();
        HashMap<String, String> monthStartAndEndTime = HelpUtils.getMonthStartAndEndTime(yearMonth);
        String startDate = monthStartAndEndTime.getOrDefault("startDate","");
        String endDate = monthStartAndEndTime.getOrDefault("endDate","");
        //统计本月订单金额
        HashMap<String, Object> orderStatistics = this.baseMapper.orderStatistics(params.getShopId(), startDate, endDate);
        double payPrice = Double.parseDouble(orderStatistics.get("payPrice").toString());
        double appointPrice = Double.parseDouble(orderStatistics.get("appointPrice").toString());
        double totalAmount = BigDecimalMathUtil.add(payPrice,appointPrice);//本月营业额，包括订单金额和定金
        orderDetailVo.setTotalAmount(totalAmount);
        params.setStartTime(startDate);
        params.setEndTime(endDate);
        PageModel<OrderListPageVo> orderListPageVoPageModel = orderListPage(params);
        orderDetailVo.setOrderList(orderListPageVoPageModel);
        return orderDetailVo;
    }

    /**
     * 买单记录page
     * @param params
     * @return
     */
    public PageModel<OrderListPageVo> orderListPage(OrderListSearchParams params){
        Map<String,Object> pageMap = new HashMap<>();
        pageMap.put("page",String.valueOf(params.getPage()));
        pageMap.put("pageSize",String.valueOf(params.getPageSize()));

        Page<OrderListPageVo> list = this.baseMapper.orderListPage(
                new PageQuery<Order>(pageMap).getPage(),params);
        List<OrderListPageVo> records = list.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageModel<>(list, new ArrayList<>());
        }
        return new PageModel<>(list, records);
    }

    /**
     * 门店pc订单列表
     * @param params
     * @return
     */
    public PageModel<ShopOrderListPageVo> shopPcOrderList(ShopOrderListSearchParams params){
        Map<String,Object> pageMap = new HashMap<>();
        pageMap.put("page",String.valueOf(params.getPage()));
        pageMap.put("pageSize",String.valueOf(params.getPageSize()));

        String shopId = userService.getGlobalShopId();
        params.setShopId(shopId);
        Page<ShopOrderListPageVo> list = this.baseMapper.shopPcOrderList(
                new PageQuery<Order>(pageMap).getPage(),params);
        List<ShopOrderListPageVo> records = list.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageModel<>(list, new ArrayList<>());
        }
        return new PageModel<>(list, records);
    }

    /**
     * 订单走势图
     * @param type 0 本周 1 本月
     * @return
     */
    public List<Map<String,Double>> orderTendencyChart(Integer type){
        String shopId = userService.getGlobalShopId();
        int startNum = (type == 0 ) ? 7 : 30;
        List<Map<String, Double>> mapList = new ArrayList<>();
        for (int i = 1; i <=startNum ; i++) {
            HashMap<String, Double> stringIntegerHashMap = new HashMap<>();
            String today = DateUtil.today();
            DateTime date = DateUtil.offsetDay(DateUtil.parse(today), -i);
            String dateStr = DateUtil.formatDate(date);
            String startDate = dateStr + " 00:00:00";
            String endDate = dateStr + " 23:59:59";
            HashMap<String, Object> orderStatistics = this.baseMapper.orderStatistics(shopId, startDate, endDate);
            double payPrice = Double.parseDouble(orderStatistics.get("payPrice").toString());
            double appointPrice = Double.parseDouble(orderStatistics.get("appointPrice").toString());
            double totalPrice = BigDecimalMathUtil.add(payPrice, appointPrice);
            stringIntegerHashMap.put(dateStr,totalPrice);
            mapList.add(stringIntegerHashMap);
        }
        return mapList;
    }

    /**
     * 手动录入线下订单
     * @param params
     * @return
     */
    public boolean offlineOrder(SaveOfflineOrderParams params){
        String shopId = userService.getGlobalShopId();
        try {
            Order order = ConvertUtils.sourceToTarget(params, Order.class);
            order.setOrderNo(HelpUtils.getOrderNumber());
            order.setShopId(shopId);
            String mobile = params.getMobile();
            User user = userService.getOne(new QueryWrapper<User>()
                    .lambda()
                    .eq(User::getMobile, mobile),false);
            if(Objects.nonNull(user)){
                order.setUserId(user.getUserId());
            }
            order.setHasPay(1);
            return this.save(order);
        } catch (Exception e) {
            log.info("手动录入订单失败："+e.getMessage());
        }
        return false;
    }

    /**
     * 向用户发起收款
     * @param userId
     * @param payPrice
     * @return
     */
    public boolean startPayToUser(String userId,Double payPrice){
        if(payPrice < 0.01){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"收款金额异常");
        }
        UserGroup userGroup = userGroupService.getOne(new QueryWrapper<UserGroup>()
                .lambda()
                .eq(UserGroup::getUserId, userId)
                .eq(UserGroup::getIsPay, 0));
        if(Objects.isNull(userGroup)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"该玩家没有需要支付的订单");
        }
        Order noPayOrder = this.getOne(new QueryWrapper<Order>().lambda()
                .eq(Order::getUserGroupId, userGroup.getGroupId())
                .eq(Order::getUserId, userId)
                .eq(Order::getHasPay, 0), false);
        if(Objects.nonNull(noPayOrder)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"该玩家已经买过单了，等待他支付");
        }
        try {
            Order order = new Order();
            order.setTotalPrice(payPrice);
            //选满足金额的面值最大优惠券
            UserCoupon userCoupon = userService.autoGetOneUserCoupon(userId, payPrice);
            if(Objects.nonNull(userCoupon)){
                //支付金额减去优惠券
                payPrice = BigDecimalMathUtil.sub(payPrice,userCoupon.getFaceValue());
                order.setDiscountPrice(userCoupon.getFaceValue());
                order.setUserCouponId(userCoupon.getUserCouponId());
            }
            //定金
            UserAppointOrder appointOrder = userAppointOrderService.getOne(new QueryWrapper<UserAppointOrder>()
                    .lambda()
                    .eq(UserAppointOrder::getUserId, userId)
                    .eq(UserAppointOrder::getGroupId, userGroup.getGroupId())
                    .eq(UserAppointOrder::getHasPay,1));
            order.setOrderNo(HelpUtils.getOrderNumber());
            order.setUserId(userId);
            order.setUserGroupId(userGroup.getGroupId());
            order.setScriptId(userGroup.getScriptId());
            order.setShopId(userGroup.getShopId());
            order.setPayPrice(payPrice);
            order.setMasterId(userGroup.getMasterId());
            order.setAppointPrice(appointOrder.getPayAmount());
            order.setCreatedTime(new Date());
            return this.save(order);
        } catch (Exception e) {
            log.info("发起收款失败："+e.getMessage());
        }
        return false;
    }

    /**
     * 店铺PC发起收款，不要默认给选优惠券
     * @param userId
     * @param payPrice
     * @return
     */
    public boolean startPayToUserForPc(String userId,Double payPrice){
        if(payPrice < 0.01){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"收款金额异常");
        }
        UserGroup userGroup = userGroupService.getOne(new QueryWrapper<UserGroup>()
                .lambda()
                .eq(UserGroup::getUserId, userId)
                .eq(UserGroup::getIsPay, 0));
        if(Objects.isNull(userGroup)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"该玩家没有需要支付的订单");
        }
        Order noPayOrder = this.getOne(new QueryWrapper<Order>().lambda()
                .eq(Order::getUserGroupId, userGroup.getGroupId())
                .eq(Order::getUserId, userId)
                .eq(Order::getHasPay, 0), false);
        if(Objects.nonNull(noPayOrder)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"该玩家已经买过单了，等待他支付");
        }
        try {
            Order order = new Order();
            order.setTotalPrice(payPrice);
            //定金
            UserAppointOrder appointOrder = userAppointOrderService.getOne(new QueryWrapper<UserAppointOrder>()
                    .lambda()
                    .eq(UserAppointOrder::getUserId, userId)
                    .eq(UserAppointOrder::getGroupId, userGroup.getGroupId())
                    .eq(UserAppointOrder::getHasPay,1));
            order.setOrderNo(HelpUtils.getOrderNumber());
            order.setUserId(userId);
            order.setUserGroupId(userGroup.getGroupId());
            order.setScriptId(userGroup.getScriptId());
            order.setShopId(userGroup.getShopId());
            order.setPayPrice(payPrice);
            order.setMasterId(userGroup.getMasterId());
            order.setAppointPrice(appointOrder.getPayAmount());
            order.setCreatedTime(new Date());
            return this.save(order);
        } catch (Exception e) {
            log.info("发起收款失败："+e.getMessage());
        }
        return false;
    }

    /**
     * 统计活跃用户
     * @param shopId
     * @param dateTime
     * @return
     */
    public int countActiveUser(String shopId,String dateTime){
        return this.baseMapper.countActiveUser(shopId,dateTime);
    }

    /**
     * 结账回显页
     * @param userId
     * @param groupId
     * @return
     */
    public CheckOutUserOrderDetailVo checkOutDetail(String userId,String groupId){
        Order order = this.getOne(new QueryWrapper<Order>()
                .lambda()
                .eq(Order::getUserId, userId)
                .eq(Order::getUserGroupId, groupId));
        if(Objects.isNull(order)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"请先向该玩家发起收款");
        }
        UserOrderDetailVo userOrderDetailVo = this.baseMapper.orderDetail(order.getOrderId());
        CheckOutUserOrderDetailVo checkoutOrder = ConvertUtils.sourceToTarget(userOrderDetailVo, CheckOutUserOrderDetailVo.class);
        User user = userService.getById(order.getUserId());
        checkoutOrder.setUserId(order.getUserId());
        checkoutOrder.setWxName(user.getWxName());
        checkoutOrder.setHeadPortrait(user.getHeadPortrait());
        checkoutOrder.setDiscountPrice(order.getDiscountPrice());
        return checkoutOrder;
    }

    /**
     * 指定玩家结账
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean checkOutForUser(CheckOutUserOrderParams params){
        String userId = params.getUserId();
        String groupId = params.getUserGroupId();
        Order order = this.getOne(new QueryWrapper<Order>()
                .lambda()
                .eq(Order::getUserId, userId)
                .eq(Order::getUserGroupId, groupId));
        if(Objects.isNull(order)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"请先向该玩家发起收款");
        }
        if(order.getHasPay() == 1){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"该玩家已支付");
        }
        if(params.getDiscountWay() == 2 && StringUtils.isBlank(params.getUserCouponId())){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"请选一张优惠券");
        }
        try {
            Order checkoutOrder = ConvertUtils.sourceToTarget(params, Order.class);
            checkoutOrder.setOrderId(order.getOrderId());
            checkoutOrder.setPayTime(new Date());
            checkoutOrder.setHasPay(1);
            boolean result = this.updateById(checkoutOrder);
            if(result){
                order.setUserCouponId(params.getUserCouponId());
                handleOrder(order);
            }
            return result;
        } catch (Exception e) {
            log.info("结账失败："+e.getMessage());
        }
        return false;
    }
}